import pandas as pd
from risk_control.general_control import General_Strategy
import Indicators.ATRindicator as ATRUtil

# 吊灯止损
class Chandelier(General_Strategy):
    def __init__(self,atrbase = 2,win_loss_rate = 1.5):
        General_Strategy.__init__(self)
        self.atrbase = atrbase
        self.win_loss_rate = win_loss_rate
        self.current_profit_point = None
        self.current_loss_point = None

    def get_profit_point(self,rcInputFrame,side):
        profit_point = None
        # 吊灯止损的核心是并不设置止盈，只设置止损，因此返回None
        return profit_point
    def get_loss_point(self,rcInputFrame,side):
        # 计算传入的df的ATR
        atrframe = ATRUtil.ATR(rcInputFrame)
        atr = atrframe.iloc[-1]['ATR']
        if self.current_loss_point == None:
            ## 如果持有空仓，说明进入点为卖出，止损点在进入点之上
            if side == 0:
                loss_point = self.enter_point + atr*self.atrbase
                self.current_loss_point = loss_point
            ## 如果持有多仓，说明进入点为买入，止损点在进入点之下
            elif side == 1:
                loss_point = self.enter_point - atr*self.atrbase
                self.current_loss_point = loss_point
        # 吊灯动态更新
        else:
            ## 持有空仓，止损线向下更新
            if side == 0:
                new_loss_point =rcInputFrame.iloc[-1]['l'] - atr * self.atrbase
                # 选取当前止损点（close）与之前止损点的最低点
                if new_loss_point <self.current_loss_point:
                    loss_point = new_loss_point
                    self.current_loss_point = loss_point
            ## 多仓止损线向上更新
            elif side == 1:
                new_loss_point = rcInputFrame.iloc[-1]['h'] + atr * self.atrbase
                if new_loss_point > self.current_loss_point:
                    loss_point = new_loss_point
                    self.current_loss_point = loss_point
        return self.current_loss_point

    def set_enter_point(self,enter_point):
        self.enter_point = enter_point
    def clear(self):
        self.enter_point = None
        self.current_loss_point = None
        self.current_profit_point = None

if __name__ == '__main__':
    data_df = pd.read_csv('../data_info/bit_coin.csv', index_col=0)
    # risk = Chandelier(data_df,1)